package com.example.idie.service;

import cn.hutool.core.io.FileUtil;
import com.example.idie.bean.Response;
import com.example.idie.util.FtpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH = "C:\\Users\\Wang Zhipeng\\Desktop\\test\\";


    // 单文件上传
    @Override
    public Response<String> uploadSingleFile(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String newFileName = System.currentTimeMillis() + originalFilename;
        byte[] bytes = file.getBytes();
        FtpUtil.sshSftp(bytes, newFileName);
        System.out.println("上传成功"+newFileName);

//        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)) {
//            originalFilename = System.currentTimeMillis() + "_" + mainName + "." + extName;
//
//        }

//        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
//        file.transferTo(saveFile);
//        String url = "http://" + ip + ":" + port + "/file/download/" + originalFilename;
        return Response.success("success");
    }

    @Override
    public Response<String> download(String filename, HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH + File.separator + filename;
        if (!FileUtil.exist(filePath)) {
            return Response.fail(404, "空文件！");
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        return Response.success("下载成功");
    }

    // 批量文件上传
    @Override
    public Response<String> uploadFiles(MultipartFile[] files) {
        System.out.println(files.length);
        // 空文件判断
        if (files == null) {
            return Response.fail(404, "空文件！");
        }
        try {
            // 遍历文件数组，重命名为时间戳防止重名覆盖
            for (int i = 0; i < files.length; ++i) {
                String OriginalFilename = files[i].getOriginalFilename();
                String newFileName=System.currentTimeMillis() +OriginalFilename;
                byte[]bytes=files[i].getBytes();
                FtpUtil.sshSftp(bytes, newFileName);
                System.out.println("上传成功"+newFileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail(505, "服务器错误，文件上传失败！");
        }
        return Response.success("200");
    }


}
